from business.cookiesgetter.template.api_getter import api_app_getter, api_h5_getter
from base.request_new import RequestNew
from base.tools import NDict


def _login(mobile, api_template):
    rn = RequestNew()
    req_list = api_template(mobile)
    _vars = NDict()

    for req in req_list:
        try:
            req_data_keys = req["data"].keys()
        except AttributeError:
            req_data_keys = {}
        same = _vars.keys() & req_data_keys
        if same:
            for key in same:
                req["data"].update({key: _vars[key]})
        res, get_vars = rn.request_auto(**req)
        _vars.update(get_vars)
        if not _vars["toLogin"]:
            print(f"{mobile}未注册\n")
            raise RuntimeError()

    return _vars


def user_login(terminal: str, mobile):
    if terminal.lower() == "app":
        return _login(mobile, api_app_getter)["token"]
    if terminal.lower() == "h5":
        return _login(mobile, api_h5_getter)["cookies"]
    return None
